<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i>
                    {{pageTitle}}
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <acc-set-card></acc-set-card>
        <div class="container" :style="{'min-height': containerHeight + 'px'}">
            <vxe-toolbar>
                <template v-slot:buttons>
                    <el-button type="primary" icon="el-icon-folder-add" @click="goAdd">新增</el-button>
                    <el-button type="warning" icon="el-icon-edit" @click="goEdit">修改</el-button>
                    <el-button type="danger" icon="el-icon-delete" @click="delAllSelection">删除</el-button>
                </template>
            </vxe-toolbar>

            <div class="handler-box">
                <el-form label-width="100px" :model="query" ref="searchRuleForm">
                    <el-row>
                        <el-col :sm="20" :md="6">
                            <el-form-item label="币别" prop="currCode">
                                <div @click="showTreeDialog('币别')">
                                    <el-input v-model="query.currCode" readonly>
                                        <i slot="suffix" class="el-icon-search"></i>
                                    </el-input>
                                </div>
                            </el-form-item>
                        </el-col>

                        <el-col :sm="20" :md="6">
                            <el-form-item label="会计期间" prop="period">
                                <el-select
                                    v-model="query.period"
                                    placeholder="请选择"
                                    clearable
                                    @focus="getPeriodList"
                                >
                                    <el-option
                                        :label="item"
                                        :value="item"
                                        v-for="(item, index) in periodList"
                                        :key="index"
                                    ></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>

                        <el-col :sm="20" :md="6" align="center">
                            <el-button
                                type="primary"
                                icon="el-icon-search"
                                @click="submitForm('searchRuleForm')"
                            >搜索</el-button>
                            <el-button type="info" @click="resetForm('searchRuleForm')">重置</el-button>
                        </el-col>
                    </el-row>
                </el-form>
            </div>

            <vxe-table
                border
                resizable
                keep-source
                highlight-hover-row
                highlight-hover-column
                ref="xTree"
                row-id="id"
                height="500"
                :loading="loading"
                :radio-config="{labelField: 'name', trigger: 'row',highlight: true}"
                :data="tableData"
                @radio-change="currentChangeEvent"
            >
                <vxe-table-column type="radio" title width="60"></vxe-table-column>
                <vxe-table-column type="seq" width="60"></vxe-table-column>
                <vxe-table-column field="currCode" title="币别"></vxe-table-column>
                <vxe-table-column field="period" title="会计期间"></vxe-table-column>
                <vxe-table-column field="rate" title="汇率"></vxe-table-column>
            </vxe-table>

            <vxe-pager
                background
                auto-hidden
                size="small"
                :loading="loading"
                :current-page="pagination.pageIndex"
                :page-size="pagination.pageSize"
                :total="pagination.pageTotal"
                :layouts="['PrevPage', 'JumpNumber','NextPage', 'Total']"
                @page-change="handlePageChange"
            ></vxe-pager>
        </div>

        <currency-Search
            :isShow="showSearch"
            :dialogTitle="searchDialogTit"
            @edit="searchBack"
            @close="closeTreeDialog"
        ></currency-Search>
    </div>
</template>


<script>
import appMain from '../../../utils/app_main';
import _ from 'lodash';
import XEUtils from 'xe-utils';

export default {
    data() {
        return {
            pageTitle: '',
            containerHeight: '',
            searchDialogTit: '',
            showSearch: false,
            tableData: [
                // {
                //     currCode: 'ipsum', //币种代码
                //     id: 'aute in',
                //     period: '202004', //会计期间
                //     rate: 59.11492 //汇率
                // },
            ],
            checkTableRow: {
                // categoryId: 'string', //科目类别
                // categoryName: 'string', //科目类别名字
                // children: [], //
                // companyId: 'string', //公司id
                // currFlag: 1, //是否核算外币：0:否 1是-
                // dealFlag: 1, //是否合算往来单位：0否，1是
                // deptFlag: 1, //是否核算部门:0否，1是
                // description: 'string', //科目名称
                // drFlag: 0, //余额方向 1.借方 2.贷方
                // empFlag: 0, //是否核算人员：0否，1是
                // id: 'string', //
                // level: 0, //科目层级：最上层总账科目1，下一层为2，独立科目99
                // parentSubId: 'string', //上级科目
                // proFlag: 0, //是否合算项目：0否，1是
                // prolossFlag: 1, //结转损益方向：1.自动转出（结算没有余额） 2.不转出（结算有余额）
                // subjectId: 'string', //科目代码
                // type: 0 //科目性质:1.总账科目,总账科目有下级科目 2.明细科目，最底层 3.独立科目没有上下级科目
            },
            loading: false,
            pagination: {
                pageIndex: 1,
                pageSize: 10,
                pageTotal: 0
            },
            query: {
                currCode: '', //币种代码
                period: '' //会计期间
            },
            //会计期间
            periodList: [],
            rules: {
                currCode: [
                    { required: true, message: '请输入币别', trigger: 'change' },
                    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'change' }
                ],
                period: [{ required: true, message: '请选择', trigger: 'change' }],
                rate: [{ required: true, message: '请输入', trigger: 'change' }]
            },
            dialogVisible: false, //新增
            dialogVisibleEdit: false, //编辑科目
            ruleForm: {
                currCode: '', //币种代码
                period: '', //会计期间
                rate: '' //汇率
            }, //新增model
            editForm: {}
        };
    },
    created() {
        this.getData();
    },
    mounted() {
        var div_height = window.screen.availHeight;
        var height = div_height - 100;
        this.containerHeight = height - 200;
        this.pageTitle = this.$router.currentRoute.meta.title;
        //$refs.xTree.setAllTreeExpand(true);
    },
    methods: {
        handlePageChange({ currentPage, pageSize }) {
            this.pagination.pageIndex = currentPage;
            this.pagination.pageSize = pageSize;
            this.getData();
        },

        //点击单选方法
        currentChangeEvent({ row }) {
            this.checkTableRow = row;
            console.log('currentChangeEvent', this.checkTableRow);
        },
        getData() {
            this.loading = true;
            console.log('getData', this.loading);
            let params = {
                pageNo: this.pagination.pageIndex,
                pageSize: this.pagination.pageSize,
                record: this.query
            };

            appMain
                .currRateFindAllPage(params)
                .then(res => {
                    if (res.data.code === 20000) {
                        //TODO 测试环境使用
                        this.timer = setTimeout(() => {
                            //设置延迟执行
                            this.tableData = res.data.data.list;
                            this.pagination.pageSize = res.data.data.pageSize;
                            this.pagination.pageIndex = res.data.data.pageNum;
                            this.pagination.pageTotal = res.data.data.total;
                            this.loading = false;
                        }, 300);

                        console.log('getData tableData', this.tableData);
                    } else {
                        this.loading = false;
                        this.$message.error(res.data.message);
                    }
                })
                .catch(err => {
                    this.loading = false;
                    console.log(err);
                });
        },
        goAdd() {
            //this.dialogVisible = true;
            this.$router.push({
                path: 'currencyExchangeRateDetail'
            });
        },
        goEdit() {
            //this.$XModal.alert(this.checkTableRow.id);
            //this.$XModal.alert(JSON.stringify(this.$refs.xTree.getRadioRecord()));
            if (this.$refs.xTree.getRadioRecord() != null) {
                this.editForm = _.clone(this.$refs.xTree.getRadioRecord());
                //this.dialogVisibleEdit = true;
                this.$router.push({
                    path: 'currencyExchangeRateDetail',
                    query: {
                        id: this.editForm.id
                    }
                });
            } else {
                this.$message.info('请选择一条记录,再进行编辑');
            }
        },
        delAllSelection() {
            if (this.$refs.xTree.getRadioRecord() != null) {
                this.editForm = _.clone(this.$refs.xTree.getRadioRecord());
            } else {
                this.$message.info('请选择一条记录,再进行编辑');
                return;
            }

            // 二次确认删除
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            })
                .then(() => {
                    //请求接口删除数据
                    this.deleteRate();
                })
                .catch(() => {});
        },
        deleteRate() {
            appMain
                .currRateDelById({}, this.editForm.id)
                .then(res => {
                    if (res.data.code === 20000) {
                        this.getData();
                        this.$message.success(res.data.message);
                    } else {
                        this.$message.error(res.data.message);
                    }
                })
                .catch(err => {
                    console.log(err);
                });
        },
        getPeriodList() {
            appMain
                .accPeriodFindDefaultData()
                .then(res => {
                    if (res.data.code === 20000) {
                        this.periodList = res.data.data;
                    } else {
                        this.$message.error(res.data.message);
                    }
                })
                .catch(err => {
                    console.log(err);
                });
        },
        handleClose(done) {
            this.$confirm('确认关闭？')
                .then(_ => {
                    this.dialogVisible = false;
                    done();
                })
                .catch(_ => {});
        },
        submitForm(formName) {
            this.$refs[formName].validate(valid => {
                if (valid) {
                    if (formName == 'searchRuleForm') {
                        //新增科目
                        this.getData();
                    } else if (formName == 'ruleForm') {
                        this.addRate();
                    } else if (formName == 'editForm') {
                        this.updateRate();
                    }
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        resetForm(formName) {
            this.$refs[formName].resetFields();
        },
        // 选择
        showTreeDialog(tit) {
            console.log('showTreeDialog');
            this.searchDialogTit = tit;
            this.showSearch = true;
        },
        // 树组件搜索结果返回
        searchBack(data) {
            console.log(data.backData, 'searchTreeBack');
            this.query.currCode = data.backData.currCode;
            this.showSearch = false;
        },
        closeTreeDialog(data) {
            this.showSearch = data.showDialog;
        }
    },
    computed: {},
    watch: {
        dialogVisible(newValue, oldValue) {
            console.log('dialogVisible', newValue);
            if (newValue == false) {
                this.ruleForm = {
                    currCode: '', //币种代码
                    period: '', //会计期间
                    rate: '' //汇率
                };
                this.$refs['ruleForm'].resetFields();
                console.log('dialogVisible ruleForm', this.ruleForm);
            }
        }
    }
};
</script>

<style lang="css" scoped>
.el-card {
    height: 100%;
}

.flex-right {
    padding: 20px;
}

.handler-box {
    border: 1px solid rgb(232, 234, 236);
    padding: 5px;
    margin-bottom: 15px;
}

.tree-box .flex-left {
    padding: 0px !important;
}
</style>